import { baseUrl } from '../utils/config'
const errorCode = {
  401: '认证失败，无法访问系统资源',
  403: '当前操作没有权限',
  404: '访问资源不存在',
  default: '系统未知错误，请反馈给管理员'
}

const request = ({ url, headers, method, data, timeout, params }) => {
  let needToken = true
  if (headers && !headers.token) {
    needToken = false
  }

  if (headers && headers.token) {
    const token = wx.getStorageSync('token')
    if (!token) {
      // gotoHome()
      return new Promise((resolve, reject) => {})
    }
  }
  return new Promise((resolve, reject) => {
    wx.request({
      data: data || params,
      url: `${baseUrl()}${url}`,
      timeout: 30000,
      header: {
        'content-type': 'application/json;charset=utf-8',
        Authorization: needToken ? 'Bearer ' + wx.getStorageSync('token') : ''
      },
      method: method || 'POST',
      success: res => {
        if (res.statusCode == 200) {
          const code = res.data.code || 200
          // 获取错误信息
          const msg = errorCode[code] || res.data.msg || errorCode['default']
          if (code === 401) {
            wx.showModal({
              title: '提示',
              content: '无效的会话，或者会话已过期，请重新登录',
              success(res) {
                if (res.confirm) {
                  wx.clearStorage({
                    success: res => {
                      gotoLogin()
                    }
                  })
                }
              }
            })
          } else if (code !== 200) {
            wx.showToast({
              icon: 'error',
              title: msg
            })
          }
          resolve(res.data)
        } else {
          reject(res.data)
        }
      },
      fail: error => {
        reject(error.data)
      }
    })
  })
}

export { request }
